using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Cryptography;
using System.Text;

public class HmacAuthAttribute : Attribute, IAsyncActionFilter
{
    private const string SignatureHeader = "X-Signature";
    private const string TimeStampHeader = "X-Timestamp";

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var config = context.HttpContext.RequestServices.GetService(typeof(IConfiguration)) as IConfiguration;
        var apiKey = config?["ApiKey"] ?? "";
        var req = context.HttpContext.Request;

        if (!req.Headers.TryGetValue(SignatureHeader, out var reqSignature))
        {
            context.Result = new ContentResult { StatusCode = 401, Content = "Missing authentication headers" };
            return;
        }
        if (!req.Headers.TryGetValue(TimeStampHeader, out var reqTimetamp))
        {
            context.Result = new ContentResult { StatusCode = 401, Content = "Missing authentication headers" };
            return;
        }

        // 生成签名内容
        var computedSignature = ComputeHmacSHA256(reqTimetamp!, apiKey);

        if (!computedSignature.Equals(reqSignature, StringComparison.OrdinalIgnoreCase))
        {
            context.Result = new ContentResult { StatusCode = 401, Content = "Invalid signature" };
            return;
        }

        await next();
    }

    private static string ComputeHmacSHA256(string data, string key)
    {
        using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
        return BitConverter.ToString(hash).Replace("-", "").ToLower();
    }
}